// src/utils/serverAuth.js

const { generateToken, verifyToken } = require('./jwt');
const crypto = require('crypto');

class AuthService {
  constructor(env) {
    this.env = env;
  }

  // 生成验证码
  generateVerificationCode() {
    return Math.floor(100000 + Math.random() * 900000).toString();
  }

  // 存储验证码和其状态
  async saveVerificationRequest(type, value, code) {
    const requestId = crypto.randomUUID();
    const key = `verification:${requestId}`;
    const data = {
      type,
      value,
      code,
      status: 'pending',
      createTime: Date.now(),
      expireTime: Date.now() + 5 * 60 * 1000 // 5分钟过期
    };

    await this.env.VERIFICATION_KV.put(key, JSON.stringify(data), {
      expirationTtl: 300 // 5分钟
    });

    return requestId;
  }

  // 验证验证码
  async verifyCode(requestId, code) {
    const key = `verification:${requestId}`;
    const data = await this.env.VERIFICATION_KV.get(key, { type: 'json' });
    
    if (!data) {
      throw new Error('验证码不存在或已过期');
    }

    if (data.status !== 'pending') {
      throw new Error('验证码已使用');
    }

    if (data.code !== code) {
      throw new Error('验证码错误');
    }

    if (Date.now() > data.expireTime) {
      throw new Error('验证码已过期');
    }

    // 更新验证状态
    data.status = 'verified';
    await this.env.VERIFICATION_KV.put(key, JSON.stringify(data), {
      expirationTtl: 300
    });

    return true;
  }

  // 解密微信手机号
  async decryptPhoneNumber(code) {
    try {
      const accessToken = await this.getAccessToken();
      const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
      const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify({ code })
      });
      const data = await response.json();
      
      if (data.errcode !== 0) {
        throw new Error(data.errmsg || '获取手机号失败');
      }

      return data.phone_info.phoneNumber;
    } catch (err) {
      throw new Error('手机号解密失败: ' + err.message);
    }
  }

  // 获取微信 access_token
  async getAccessToken() {
    const key = 'wechat:access_token';
    let token = await this.env.TOKEN_KV.get(key, { type: 'json' });

    if (token && token.expireTime > Date.now()) {
      return token.accessToken;
    }

    // 重新获取 access_token
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.env.WECHAT_APP_ID}&secret=${this.env.WECHAT_APP_SECRET}`;
    const response = await fetch(url);
    const data = await response.json();

    if (data.errcode) {
      throw new Error(data.errmsg || '获取access_token失败');
    }

    token = {
      accessToken: data.access_token,
      expireTime: Date.now() + (data.expires_in - 300) * 1000 // 提前5分钟过期
    };

    await this.env.TOKEN_KV.put(key, JSON.stringify(token), {
      expirationTtl: data.expires_in - 300
    });

    return token.accessToken;
  }

  // 验证权限
  checkPermission(token, requiredPermission) {
    const decoded = verifyToken(token, this.env.JWT_SECRET);
    if (!decoded || !decoded.permissions) {
      return false;
    }
    return decoded.permissions.includes(requiredPermission);
  }
}

module.exports = AuthService;
